﻿using AutoMapper;
using B.S.Production.Domain.Entities;
using B.S.Production.ErrorCode;
using B.S.Production.Write.API.Application.Command.ProductionOrderCommand;
using MediatR;
using SqlSugar;
using SqlSugar.Extensions;
using Yitter.IdGenerator;

namespace B.S.Production.Write.API.Application.CommandHandlers.ProductionOrderCommandHandler
{
    public class AddProductionOrderCommandHandler : IRequestHandler<AddProductionOrderCommand, ApiResult<int>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="mapper"></param>
        public AddProductionOrderCommandHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddProductionOrderCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var entity = mapper.Map<ProductionOrder>(request);
            entity.ProductNumber = YitIdHelper.NextId();
            result.Data = await db.Insertable(entity).ExecuteCommandAsync();
            if(result.Data > 0)
            {
                result.Code = ApiEnums.添加成功;
                result.Msg = ApiEnums.添加成功.ToString();
            }
            else
            {
                result.Code = ApiEnums.添加失败;
                result.Msg = ApiEnums.添加失败.ToString();
            }
            return result;
        }
    }
}
